package com.jn.erp.security.sysservice.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jn.erp.common.constant.UserConstants;
import com.jn.erp.common.exception.ServiceException;
import com.jn.erp.common.utils.StringUtils;
import com.jn.erp.security.entity.SysRole;
import com.jn.erp.security.mapper.SysRoleMapper;
import com.jn.erp.security.mapper.SysUserRoleMapper;
import com.jn.erp.security.sysservice.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <pre>
 *
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/8/28 15:45
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public List<SysRole> getRolesByUser(Long userId) {
        return baseMapper.getRolesByUser(userId);
    }

    @Override
    public List<SysRole> getRolesByOrgUser(Long userId,Long orgId) {
        return baseMapper.getRolesByOrgUser(userId,orgId);
    }
    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(Long userId,Long orgId) {
        List<SysRole> perms =new ArrayList<>();
        if(orgId==0l){
            perms=baseMapper.selectRolePermissionByUserId(userId);
        }else{
            perms=baseMapper.selectRolePermissionByOrgUser(userId,orgId);
        }

        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms) {
            if (StringUtils.isNotNull(perm)) {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public List<SysRole> selectRoleList(SysRole sysRole) {
        return baseMapper.selectRoleList(sysRole);
    }

    /**
     * 校验角色名称是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean checkRoleNameUnique(SysRole role) {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        QueryWrapper<SysRole> qw=new QueryWrapper();
        qw.eq("role_name",role.getRoleName());
        qw.eq("del_flag","0");
        SysRole info = baseMapper.selectOne(qw);
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色权限是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean checkRoleKeyUnique(SysRole role) {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        QueryWrapper<SysRole> qw=new QueryWrapper();
        qw.eq("role_key",role.getRoleKey());
        qw.eq("del_flag","0");
        SysRole info = baseMapper.selectOne(qw);
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }


//    /**
//     * 新增角色菜单信息
//     *
//     * @param role 角色对象
//     */
//    public int insertRoleMenu(SysRole role) {
////        int rows = 1;
////        // 新增用户与角色管理
////        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
////        for (Long menuId : role.getMenuIds()) {
////            SysRoleMenu rm = new SysRoleMenu();
////            rm.setRoleId(role.getRoleId());
////            rm.setMenuId(menuId);
////            list.add(rm);
////        }
////        if (list.size() > 0) {
////            rows = roleMenuMapper.batchRoleMenu(list);
////        }
////        return rows;
//        return 0;
//    }

    /**
     * 批量删除角色信息
     *
     * @param roleIds 需要删除的角色ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteRoleByIds(Long[] roleIds) {
        for (Long roleId : roleIds) {
            SysRole sr= new SysRole();
            sr.setRoleId(roleId);
            checkRoleAllowed(sr);
//            checkRoleDataScope(roleId);
            SysRole role = baseMapper.selectById(roleId);
            if (countUserRoleByRoleId(roleId) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        return baseMapper.deleteBatchIds(Arrays.asList(roleIds));
    }



    /**
     * 校验角色是否允许操作
     *
     * @param role 角色信息
     */
    @Override
    public void checkRoleAllowed(SysRole role) {
        if (StringUtils.isNotNull(role.getRoleId()) && 1L == role.getRoleId()) {
            throw new ServiceException("不允许操作超级管理员角色");
        }
    }


    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countUserRoleByRoleId(Long roleId) {
        return sysUserRoleMapper.countUserRoleByRoleId(roleId);
    }

    @Override
    public List<SysRole> selectRoleOrg(SysRole sysRole) {
        return baseMapper.selectRoleOrg(sysRole);
    }
}
